import {getLength} from '../../utils/string-util';
import toast from '../../common/service/toast-service';
import {addComment} from '../../data-model/model-comment';
import page from '../../common/service/page-service';
import {eventBusGetter} from '../../utils/eventbus';
import {EVENT_BUS_KEY} from '../../common/constants';

Page({
    data: {
        commentId: '', // 针对评论去评论 针对回复去评论
        lessonId: '', // 发表评论
        courseId: '', // 课程id
        targetUid: '', // 被评论人userId
        placeholder: '' // 如果是回复显示这上值
    },
    onLoad (params) {
        this.data.commentId = params.commentId;
        this.data.lessonId = params.lessonId;
        this.data.courseId = params.courseId;
        this.data.placeholder = params.placeholder;
        this.data.targetUid = params.targetUid;
        if (params.placeholder && params.placeholder.length > 0) {
            this.setData({
                placeholder: params.placeholder
            });
        } else {
            this.setData({
                placeholder: '大量数据表明，撰写心得不仅能提高阅读书、文的效率，而且能提高科学研究和写作能力。（限1000字）'
            });
        }
    },
    formSubmit (form) {
        // TODO 发送formId
        let comment = form.detail.value.comment;
        if (comment.length === 0) {
            toast.showLoadingToast('请输入评论');
            return;
        }

        if (getLength(comment) > 2000) {
            toast.showLoadingToast('字数已达上限');
            return;
        }
        toast.showLoading();
        let params = {};
        if (this.data.commentId.length > 0) {
            params['targetId'] = this.data.commentId;
        }

        if (this.data.lessonId.length > 0) {
            params['lessonId'] = this.data.lessonId;
        }

        if (this.data.courseId.length > 0) {
            params['courseId'] = this.data.courseId;
        }

        if (this.data.targetUid.length > 0) {
            params['targetUid'] = this.data.targetUid;
        }
        params['content'] = comment;

        addComment(params)
            .then(res => {
                toast.hideLoading();
                eventBusGetter().$emit(EVENT_BUS_KEY.ADD_COMMENT_SUCCESS, {
                    comment: res
                });
                page.navigateBack();
            })
            .catch(err => {
                toast.hideLoading();
                if (err.header.msg) {
                    let errMsg = decodeURI(err.header.msg);
                    toast.showLoadingToast(errMsg);
                }
            });
    }
});
